/**
 * Package:com.goldcitynet.flex.service;
 * $Id: AbstractFlexService.java,v 1.7 2009/06/12 10:05:48 yangc Exp $
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.engine.api.as3.service;

import flex.messaging.FlexContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

/**
 * AbstractFlexService
 * <p/>
 * <p><a href="AbstractFlexService.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author: yangc $</a>
 * @version $Revision: 1.7 $
 */
public abstract class AbstractFlexService {
    private static Log log = LogFactory.getLog(AbstractFlexService.class);


    /**
     * 便捷方法取得Http Request
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        return FlexContext.getHttpRequest();
    }

    /**
     * 便捷方法取得Http Response
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        return FlexContext.getHttpResponse();
    }

    /**
     * 便捷方法取得Http Session
     *
     * @return
     */
    public HttpSession getSession() {
        return FlexContext.getHttpRequest().getSession();
    }

    /**
     * 已登录用户信息
     *
     * @return org.springframework.security.userdetails.User对象
     */
    public org.springframework.security.userdetails.User authorizedUser() {
        SecurityContext context = (SecurityContext) getSession().getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
        try {
            return (org.springframework.security.userdetails.User) context.getAuthentication().getPrincipal();
        } catch (Exception e) {
            log.debug("There no user info in the session!");
            return null;
        }
    }

    /**
     * 用户是否认证（登录）
     *
     * @return 已登录返回true，否则返回false
     */
    public boolean isAuthorized() {
        return authorizedUser() != null;
    }

    public String getUsername(){
        return authorizedUser().getUsername();
    }

}
